package org.durcframework.rms.service;

import java.util.Collections;
import java.util.List;

import org.durcframework.core.expression.ExpressionQuery;
import org.durcframework.core.expression.subexpression.ValueExpression;
import org.durcframework.core.service.CrudService;
import org.durcframework.rms.constant.RoleType;
import org.durcframework.rms.dao.RUserRoleDao;
import org.durcframework.rms.entity.RUserRole;
import org.durcframework.rms.entity.SetUserRole;
import org.durcframework.rms.entity.UserRoleParam;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

@Service
public class RUserRoleService extends CrudService<RUserRole, RUserRoleDao> {
	
	/**
	 * 设置用户角色
	 * 1. 先设置用户组角色
	 * 2. 设置个人角色
	 * @param setUserRole
	 */
	public void setUserRoles(SetUserRole setUserRole) {
		UserRoleParam groupUserRole = new UserRoleParam();
		groupUserRole.setRoleIds(setUserRole.getGroupRoleIds());
		groupUserRole.setRoleType(RoleType.GROUP);
		groupUserRole.setUsername(setUserRole.getUsername());
		this.setUserRole(groupUserRole);
		
		UserRoleParam personRole = new UserRoleParam();
		personRole.setRoleIds(setUserRole.getPersonRoleIds());
		personRole.setRoleType(RoleType.PERSON);
		personRole.setUsername(setUserRole.getUsername());
		this.setUserRole(personRole);
	}

	/**
	 * 设置用户角色
	 */
	public void setUserRole(UserRoleParam userRoleParam) {
		this.getDao().delAllUserRole(userRoleParam);

		if (StringUtils.isEmpty(userRoleParam.getUsername())
				|| CollectionUtils.isEmpty(userRoleParam.getRoleIds())) {
			return;
		}

		this.getDao().setUserRole(userRoleParam);
	}
	
	/**
	 * 获取用户角色
	 * @param username
	 * @return
	 */
	public List<RUserRole> getUserRole(String username) {
		if(StringUtils.isEmpty(username)){
			return Collections.emptyList();
		}
		ExpressionQuery query = ExpressionQuery.buildQueryAll();
		query.add(new ValueExpression("username", username));
		
		return this.find(query);
	}
	
	public List<RUserRole> getUserRoleByRoleId(int roleId){
		ExpressionQuery query = ExpressionQuery.buildQueryAll();
		query.add(new ValueExpression("role_id", roleId));
		return this.find(query);
	}
	
	public void delByRoleId(int roleId){
		this.getDao().delByRoleId(roleId);
	}
	
	/**
	 * 删除用户组成员角色
	 * @param username
	 */
	public void delGroupRoleByUser(String username) {
		this.getDao().delGroupRoleByUser(username);
	}

}
